package com.community.web.user.controller.login;

import com.community.common.login.LoginUserHolder;
import com.community.common.result.Result;
import com.community.model.entity.User;
import com.community.web.user.service.LoginService;
import com.community.web.user.vo.LoginVo;
import com.community.web.user.vo.RegisterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录模块")
@RestController
@RequestMapping("/user/")
public class LoginController {

    @Autowired
    private LoginService service;

    @ApiOperation("用户登录")
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String token = service.login(loginVo);
        return Result.ok(token);
    }

    @ApiOperation("用户注册")
    @PostMapping("register")
    public Result register(@RequestBody RegisterVo registerVo) {
        service.register(registerVo);
        return Result.ok();
    }

    @ApiOperation("检查手机号是否已经注册")
    @PostMapping("register/check")
    public Result checkPhone(@RequestParam String phone) {
        service.checkPhone(phone);
        return Result.ok();
    }

    @GetMapping("login/sendCode")
    @ApiOperation("发送短信验证码")
    public Result sendCode(@RequestParam String phone) {
        service.sendCode(phone);
        return Result.ok();
    }

    @ApiOperation("获取用户名")
    @GetMapping("username")
    public Result<Map> getUsername() {
        String username = service.getUsername(LoginUserHolder.getLoginUser().getUserId());
        HashMap<Object, Object> map = new HashMap<>();
        map.put("username", username);
        return Result.ok(map);
    }

    @ApiOperation("校验验证码")
    @PostMapping("login/checkCode")
    public Result checkCode(@RequestParam String code, @RequestParam String phone) {
        service.checkCode(code, phone);
        return Result.ok();
    }

    @ApiOperation("忘记密码")
    @PostMapping("login/password")
    public Result updatePassword(@RequestBody User user) {
        service.updatePassword(user);
        return Result.ok();
    }
}
